package com.tqw.gateway.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.tqw.auth.feign.AuthFegin;
import com.tqw.gateway.constant.SecurityConstants;
import com.tqw.gateway.util.JWTUtil;
import org.apache.http.cookie.Cookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @Author: czm
 * @Date: 2022/04/14/15:29
 * @Description:用于请求的全局过滤器
 */
@Component
public class GatewayRequestFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private AuthFegin authFegin;




    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求与响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //放行不需要登录路由
        String uri = request.getURI().getPath();
        if ( uri.startsWith("/tqw/auth/") || uri.equals("/tqw/item/itemCat/findItemCatList/3")
            || uri.startsWith("/tqw/es/") || uri.startsWith("/tqw/item/itemDesc") || uri.equals("/tqw/item/file/upload")){
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst(SecurityConstants.AUTHORIZATION_KEY);
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.setComplete();
            return chain.filter(exchange);
        }
        String substringToken = token.substring(7);
        System.out.println(substringToken);
        Long expire = redisTemplate.getExpire(substringToken);
        if (expire!=-2){
            boolean expired = JWTUtil.isExpired(token);
            if (!expired){
                return chain.filter(exchange);
            }
            String s = redisTemplate.opsForValue().get(token);
            System.out.println("s:"+s);
            String newToken = authFegin.refreshToken(Integer.valueOf(s));

            redisTemplate.opsForValue().set(newToken,s, Duration.ofHours(3));
            response.getHeaders().add("token",newToken);
            response.getHeaders().set("Access-Control-Expose-Headers","token");
            response.setComplete();
            return chain.filter(exchange);
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.setComplete();
        return chain.filter(exchange);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
